import {ref} from 'vue';
import axios from 'axios';

/**
 * MockAPI：https://dog.ceo/api/breeds/image/random
 * {
    "message": "https://images.dog.ceo/breeds/cockapoo/gracie.jpg",
    "status": "success"
   }
 * @param url 
   @description 功能复用，异步读取数据
 * @returns 
 */
function useURLLoader<T>(url: string) {
    const result = ref<T | null>(null);
    const loading = ref(true);
    const loaded = ref(false);
    const error = ref(null);
    
    axios.get(url).then((rawData) => {
        loading.value = false;
        loaded.value = true;
        result.value = rawData.data;
    }).catch((e) => {
        error.value = e;
        loading.value = false;
    });

    return {
        loading,
        loaded,
        result,
        error
    }
}

export default useURLLoader;